package com.lawliet.example.config;

import com.lawliet.example.filter.CustomFilter;
import com.lawliet.example.filter.JwtAuthenticationTokenFilter;
import com.lawliet.example.service.impl.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig  {

    @Autowired
    private  JwtAuthenticationTokenFilter jwtFilter;

    @Autowired
    private UserDetailsService userDetailsService;


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .addFilterBefore(jwtFilter,UsernamePasswordAuthenticationFilter.class)//过滤器配置，将自定义过滤器排在用户密码验证过滤器之前
                .csrf().disable()//禁用csrf
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .authorizeRequests()
                .requestMatchers("/api/auth/**","/user/**",
                        "/swagger-ui/**","/v3/**").permitAll()  // 登录和注册,接口文档不需要认证
                .anyRequest().authenticated()  // 其他请求需要认证
                .and()
                .formLogin(formLogin->formLogin.disable())
                .logout(logout->logout.disable());

        return http.build();
    }


    // CORS 配置（允许所有来源，仅测试用！生产环境要限制域名）
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);  // 允许携带Cookie（如JWT）
//        config.addAllowedOrigin("http://localhost:3000/");  // 允许的前端地址（或 * 测试用）
        config.setAllowedOrigins(Arrays.asList(
                "http://localhost:3000",
                "http://localhost:3001"
        ));
        config.addAllowedHeader("*");      // 允许所有请求头
        config.addAllowedMethod("*");      // 允许所有HTTP方法（GET/POST等）

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);  // 对所有路径生效
        return source;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用BCrypt密码加密
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(userDetailsService)  // 使用自定义的 UserDetailsService
                .passwordEncoder(passwordEncoder())
                .and()
                .build();
    }

}
